package com.yky.action.common;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.InterceptorRefs;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.yky.action.base.BaseActionSupport;
import com.yky.entity.Organization;
import com.yky.entity.OrganizationRecords;
import com.yky.entity.User;
import com.yky.service.admin.OrganizationRecordsService;
import com.yky.service.admin.OrganizationService;
import com.yky.service.admin.UserService;

@ParentPackage("perInterceptor")
@InterceptorRefs( { @InterceptorRef("sessionStack") })
@Namespace(value = "/admin")
@Results( { @Result(name = "public_index", type = "redirect", location = "/index.jsp") })
public class LoginAction extends BaseActionSupport {

	private static final long serialVersionUID = 1L;

	private String username;
	private String password;

	@Autowired
	private UserService userService;
	@Autowired
	private OrganizationRecordsService organizationRecordsService;
	@Autowired
	private OrganizationService organizationService;

	// 用户登录
	public String loginSystem() throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		response.setCharacterEncoding("UTF-8");
		String resultString = "";
		try {
			List<User> list = userService.findByPropertys(
					"o.username=? and o.password=?", new Object[] { username,
							password });
			if (list.size() > 0) {
				User aUser = list.get(0);
				aUser.setPassword(null);
				List<OrganizationRecords> organizationRecordsList = organizationRecordsService.findByPropertys(
						"o.organization=?", new Object[] { aUser.getOrganization()});
				int organizationRecordsStatus = 0;
				if (null != organizationRecordsList && organizationRecordsList.size() > 0) {
					organizationRecordsStatus = organizationRecordsList.get(0).getStatus();
				}
				String isApprovalStemCellsInstitutions = "0";  //是否批准的干细胞临床研究机构
				if("0".equals(aUser.getRoleType().toString()) || "1".equals(aUser.getRoleType().toString())){
					isApprovalStemCellsInstitutions= "1";
				}else{
					List<Organization> organizationList = organizationService.findByPropertys(
							"o.id=?", new Object[] { aUser.getOrganization().getId()});
					if (null != organizationList && organizationList.size() > 0) {
						isApprovalStemCellsInstitutions = organizationList.get(0).getIsApprovalStemCellsInstitutions().toString();
					}
				}
				// 登录成功
				HttpSession session = request.getSession(false);
				// 直到你决定废弃旧的，开始新的为止，一直用 getSession(false)
				if (session != null && !session.isNew()) { // 加入 isNew()
					HttpSession sessionOld = session;
					sessionOld.invalidate(); // 废弃旧的 session
					session = request.getSession(true); // 开始一个新的 session
					// TODO, 需要的话，copy 旧 session 的一些内容，到新 session
					// 至少，你要复制登陆标示，常常是，username attribute
					// 和你的应用逻辑需要的attributes,比如 shopping cart 等；
					

					if (aUser.getStatus() == 0) {
						resultString = "该用户信息正在审查中，请耐心等待！";
					} else if (aUser.getStatus() == 2) {
						session.setAttribute("username", aUser.getUsername());
						session.setAttribute("user", aUser);
						session.setAttribute("organizationRecordsStatus", organizationRecordsStatus);
						session.setAttribute("isApprovalStemCellsInstitutions", isApprovalStemCellsInstitutions);
						resultString = "/admin/user/user_login_edit.jsp";
					} else if (aUser.getStatus() == 1) {
						session.setAttribute("username", aUser.getUsername());
						session.setAttribute("user", aUser);
						session.setAttribute("organizationRecordsStatus", organizationRecordsStatus);
						session.setAttribute("isApprovalStemCellsInstitutions", isApprovalStemCellsInstitutions);
						resultString = "/index/main.jsp";
					}
				}

			} else {
				resultString = "用户名或密码错误！";
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		response.getWriter().write(resultString);

		return null;
	}

	// 退出系统
	public String exitSystem() throws IOException {
		HttpServletRequest request = ServletActionContext.getRequest();
		request.getSession(true).removeAttribute("username");
		request.getSession(true).removeAttribute("user");
		return "public_index";
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
